import json
import re

from django.http import JsonResponse, HttpResponse
from django.views import View
from django_redis import get_redis_connection

import random
import logging

from Lovehome_Max_Shanghai.libs.captcha.captcha import captcha
from celery_tasks.yuntongxun.ccp_sms import CCP
from six_it.models import User

logger = logging.getLogger("django")


class ImageCodeView(View):
    # 图形验证码

    def get(self, request):
        cur = request.GET.get("cur")
        pre = request.GET.get("pre")
        text, image = captcha.generate_captcha()

        redis_conn = get_redis_connection("verify_code")

        redis_conn.setex("code_%s" % cur, 300, text)
        logger.info('图形验证码 %s'%text)
        return HttpResponse(image, content_type="image/jpg")


class MobilesmsView(View):

    def post(self, request):
        dict = json.loads(request.body)
        mobile = dict.get("mobile")
        id = dict.get("id")
        text = dict.get("text")

        if not all([mobile, id, text]):
            return JsonResponse({"errno": "4103",
                                 "errmsg": "缺少必传参数"})

        if not re.match(r'^1[3-9]\d{9}$', mobile):
            return JsonResponse({'errno': 4103,
                                 'errmsg': 'mobile格式有误'})

        try:
            User.objects.get(mobile=mobile)
            return JsonResponse({'errno': 4003,
                                 'errmsg': '手机号已注册'})
        except Exception:

            redis_conn = get_redis_connection("verify_code")

            redis_send = redis_conn.get("send_%s" % mobile)

            if redis_send:
                return JsonResponse({"errno": "4201",
                                     "errmsg": "短信发送频繁"})

            image_text = redis_conn.get("code_%s" % id)

            if not image_text:
                return JsonResponse({"errno": "4002",
                                     "errmsg": "图形验证码过期"})

            try:
                redis_conn.delete("code_%s" % id)
            except Exception as e:
                logger.error(e)

            if image_text.decode().lower() != text.lower():
                return JsonResponse({"errno": "4103",
                                     "errmsg": "图形验证码错误"})

            sms_code = '%06d' % random.randint(0, 999999)

            logger.info('手机验证码_%s'% sms_code)

            pl = redis_conn.pipeline()
            pl.setex("sms_%s" % mobile, 300, sms_code)
            pl.setex("send_%s" % mobile, 60, 1)
            pl.execute()

            CCP().send_template_sms(mobile, [sms_code, 5], 1)

            return JsonResponse({"errno": "0",
                                 "errmsg": "发送成功"
                                 })
